#include <head.h>
#include "./wrap.h"
#define SERVER_SOCKET "server.socket"
#define CLIENT_SOCKET "client.socket"
void fn(char *p);

int main(int argc, char **argv)
{
    char buf[100];
    int serversocket = Socket(AF_UNIX, SOCK_STREAM, 0);
    struct sockaddr_un addr;
    unlink(SERVER_SOCKET);
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, SERVER_SOCKET);
    socklen_t len = offsetof(struct sockaddr_un, sun_path) + strlen(SERVER_SOCKET);
    int r;
    unlink(SERVER_SOCKET);
    r = Bind(serversocket, (struct sockaddr *)&addr, len);
    Listen(serversocket, 10);
    struct sockaddr_un client;
    while (1)
    {
        socklen_t l = sizeof(client);
        memset(&client, 0, sizeof(client));
        int cfd = Accept(serversocket, (struct sockaddr *)&client, &l);
        len -= offsetof(struct sockaddr_un, sun_path);
        // client.sun_path[len] = 0;
        printf("New connection from %s\n", client.sun_path);
        while (1)
        {
            CLEAR_ARRAY(buf);
            int len = Read(cfd, buf, sizeof(buf));
            if(len ==0){
                Close(cfd);
                break;
            }
            if (len > 0)
            {
                write(STDOUT_FILENO, buf, len);
                fn(buf);
                Write(cfd, buf, len);
            }
        }
    }
    close(serversocket);
    return 0;
}
void fn(char *p)
{
    if (!p)
    {
        return;
    }
    while (*p)
    {
        *p = toupper(*p);
        p++;
    }
}
